package com.app.couponsharelife.ui.adapter

import androidx.databinding.DataBindingUtil
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.CommonProblemBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.databinding.ProblemListItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener

/**
 * Created by guluwa on 2018/11/24.
 */
class ProblemListAdapter(val list: MutableList<Any>,
                         private val listener: OnClickListener) :
        androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {

    fun setData(data: List<Any>) {
        list.clear()
        list.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return when (viewType) {
            0 -> ViewHolderTip(DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.page_list_tip_item, parent, false))
            else -> ViewHolder(DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.problem_list_item, parent, false))
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun getItemViewType(position: Int): Int {
        return if (list[position] is PageTipBean) 0 else 1
    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == 0) {
            (holder as ViewHolderTip).databinding.pageTipBean = list[position] as PageTipBean
        } else {
            val commonProblemBean = list[position] as CommonProblemBean
            (holder as ViewHolder).databinding.mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(holder.itemView.context)
            holder.databinding.mRecyclerView.adapter = ProblemListDetailAdapter(commonProblemBean.faqs)
            holder.databinding.mRecyclerView.visibility = if ((list[position] as CommonProblemBean).isOpen) View.VISIBLE else View.GONE
            holder.databinding.mIndicatorView.visibility = if ((list[position] as CommonProblemBean).isOpen) View.VISIBLE else View.GONE
            holder.databinding.tvProblem.text = commonProblemBean.name
        }
    }

    inner class ViewHolder(val databinding: ProblemListItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.clProblemType.setOnClickListener {
                if (adapterPosition != -1) {
                    (list[adapterPosition] as CommonProblemBean).isOpen = !(list[adapterPosition] as CommonProblemBean).isOpen
                    notifyItemChanged(adapterPosition)
                }
            }
        }
    }
}